﻿///////////////////////////////////////////////////////////////////////////////////////
// Author: skzheng
// Date:   2011-05-05
// Description: 存放扩展方法
// ---------------------
// History
// 2011-04-06 skzheng Create
///////////////////////////////////////////////////////////////////////////////////////
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Data.Common;
using System.Text.RegularExpressions;
using System.Linq.Expressions;

namespace CN.Commons
{
    public static class MethodExtend
    {
        /// <summary>
        /// DataContext扩展方法--提交数据到数据库并返回是否成功
        /// </summary>
        /// <param name="t"></param>
        /// <returns>是否成功，true:提交成功，false:提交失败</returns>
        public static bool SubmitChangesWithReturnValue(this DataContext t)
        {
            try
            {
                t.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 使用Lambda Expression批量删除数据
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public static int DeleteOnSubmit(this DataContext dc, IQueryable query)
        {
            DbCommand com = dc.GetCommand(query);

            Regex reg = new Regex("^SELECT[\\s]*(?<Fields>.*)[\\s]*FROM[\\s]*(?<Table>.*)[\\s]*AS[\\s]*(?<TableAlias>.*)[\\s]*WHERE[\\s]*(?<Condition>.*)",
                                    RegexOptions.IgnoreCase);

            Match match = reg.Match(com.CommandText);

            if (!match.Success)
                throw new ArgumentException("Cannot delete this type of collection");

            string table = match.Groups["Table"].Value.Trim();
            string tableAlias = match.Groups["TableAlias"].Value.Trim();
            string condition = match.Groups["Condition"].Value.Trim().Replace(tableAlias, table);

            com.CommandText = string.Format("DELETE FROM {0} WHERE {1}", table, condition);

            if (com.Connection.State != System.Data.ConnectionState.Open)
                com.Connection.Open();

            return com.ExecuteNonQuery();
        }

        /// <summary>
        /// 使用Lambda Expression批量删除数据
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="table"></param>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public static int DeleteOnSubmit<TEntity>(this Table<TEntity> table, Expression<Func<TEntity, bool>> predicate)
            where TEntity : class
        {
            IQueryable query = table.Where(predicate);

            return table.Context.DeleteOnSubmit(query);
        } 
    }
}
